package 哈希表;

import java.util.HashMap;
import java.util.Map;

/**
 * 力扣 454 Ⅱ
 *
 * @Author zxl
 * @Date 2022/1/17 20:58
 * @Desc 给出四个长度相同的数组，找出有集中元组可以使: A[i]+B[j]+C[k]+D[l]=0
 */
public class 四数相加 {

    public static void main(String[] args) {
        // 输入：
        int[] arrayA = {3, 1, 4};
        int[] arrayB = {-2, 4, 3};
        int[] arrayC = {-1, 3, 2};
        int[] arrayD = {3, -2, 0};
        // 输出：2
        System.out.println("结果：" + findSum(arrayA,arrayB,arrayC,arrayD));
    }

    public static int findSum(int[] arrayA, int[] arrayB, int[] arrayC, int[] arrayD) {
        Map<Integer, Integer> integerMap = new HashMap<>();
        for (int a : arrayA) {
            for (int b : arrayB) {
                int sumAB = a + b;
                Integer times = integerMap.get(sumAB);
                if (times == null) {
                    integerMap.put(sumAB, 1);
                } else {
                    integerMap.put(sumAB, times + 1);
                }
            }
        }
        int count = 0;
        for (int c : arrayC) {
            for (int d : arrayD) {
                int sumCD = c + d;
                if (integerMap.containsKey(0 - sumCD)) {
                    count += integerMap.get(0 - sumCD);
                }
            }
        }
        return count;
    }
}
